<template>
  <div>
    <!-- 头部 -->
    <div class="address-top">
      <p @click="back">取消</p>
      <p>群成员</p>
      <p @click="finish">{{topVal}}</p>
    </div>
    <!-- 头部 end -->
    <header class="padd15">好友</header>
    <div class="white padd15">
      <div v-for="(val,key) in lastArr" :key="key" class="flex list"
           @click="selectMemers(val,key)">
        <div class="round"
             :class="{select:selectArr.includes(val.To_Account),noSelect:type==='add'&&!val.selectable}"></div>
        <img class="user-icon" :onerror="defaultImg" :src="val.Tag_Profile_IM_Image" alt="">
        <p class="flex1">{{val.Tag_Profile_IM_Nick}}</p>
      </div>
    </div>
  </div>
</template>
<style lang="less" rel="stylesheet/less" scoped>
  header {
    line-height: .27rem;
    color: #818181;
  }

  .list {
    align-items: center;
    height: .6rem;
    &:nth-last-child(1) {
      p {
        border-bottom: none;
      }
    }
    .round {
      width: .2rem;
      height: .2rem;
      border-radius: 50%;
      border: .005rem solid #EDEDED;
      margin-right: .1rem;
      box-sizing: border-box;
    }
    .user-icon {
      width: .4rem;
      height: .4rem;
      margin-right: .1rem;
    }
    p {
      font-size: .16rem;
      color: #4A4A4A;
      line-height: .6rem;
      height: .6rem;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      border-bottom: .005rem solid #E6E6E6;
    }

    .select {
      background: url("../../assets/img/group/select.png") no-repeat center center;
      background-size: .2rem .2rem;
      border: 0;
    }
    .noSelect {
      background: url("../../assets/img/group/no-select.png") no-repeat center center;
      background-size: .2rem .2rem;
      border: 0;
    }
  }


</style>
<script>
  import {checkStatus} from '../../assets/js/login';
  import {getProfile} from '../../assets/js/commonWebim'
  import {Toast, MessageBox} from 'mint-ui'
  import Client from '@/assets/js/common';
  
  export default {
    data () {
      return {
        defaultImg: Client.defaultImg,
        groupLists: [],  // 群数据
        selectArr: [], // 勾选数据
        loginInfo: {},
        groupId: '',  // 群ID
        friendLists: [],  // 好友数据
        type: '', // add del
        topVal: '添加',
        lastArr: []  // 最终显示的数据
      }
    },
    mounted () {
      this.groupId = this.$route.query.groupId  // 群ID
      this.type = this.$route.query.type  // 添加 删除
      this.topVal = this.type === 'add' ? '添加' : '完成'
      checkStatus((loginInfo) => {
        this.loginInfo = loginInfo
        this.getGroupMemberInfo(this.groupId) //获取群成员
        this.getFriendList(this.loginInfo)  // 好友列表
      });
    },
    methods: {
      // 返回
      back(){
        history.back()
      },
      // 选择成员
      selectMemers(val, key){
        if (this.type === 'add') {
          if (!val.selectable) return // 不可选的跳过
        }
        // 多选
        if (!this.selectArr.includes(val.To_Account)) {
          this.selectArr.push(val.To_Account)
        } else {
          let index = this.selectArr.indexOf(val.To_Account)
          this.selectArr.splice(index, 1)
        }
      },
      // 获取当前群组成员
      getGroupMemberInfo(group_id) {
        let That = this;
        var options = {
          'GroupId': group_id,
          'Offset': 0, // 必须从0开始
          'Limit': 2000,
          'MemberInfoFilter': [
            'Account',
            'Role',
            'JoinTime',
            'LastSendMsgTime',
            'ShutUpUntil'
          ]
        };
        webim.getGroupMemberInfo(
          options,
          function (resp) {
            if (resp.MemberNum <= 0) {
              Toast('该群组目前没有成员');
              return;
            }
            var data = [];
            for (var i in resp.MemberList) {
              var account = resp.MemberList[i].Member_Account;
              var role = webim.Tool.groupRoleEn2Ch(resp.MemberList[i].Role);
              let part = resp.MemberList[i].Role;
              var join_time = webim.Tool.formatTimeStamp(resp.MemberList[i].JoinTime);
              var shut_up_until = webim.Tool.formatTimeStamp(resp.MemberList[i].ShutUpUntil);
              if (shut_up_until == 0) {
                shut_up_until = '-';
              }

              data.push({
                GId: group_id,
                GroupId: webim.Tool.formatText2Html(group_id),
                Member_Account: webim.Tool.formatText2Html(account),
                Role: role,
                JoinTime: join_time,
                ShutUpUntil: shut_up_until,
                Part: part
              });
            }
            // 取出群账号
            let arr = []
            data.forEach(val => {
              arr.push(val.Member_Account)
            })
            // 个人信息
            getProfile(arr, function (res) {
              That.groupLists = res;
              console.log('群列表', res);
              // 获取群主账号信息
              let ownerData = data.filter(val => val.Part === 'Owner')
              let OwnerALLData = That.groupLists.filter(val => val.To_Account === ownerData[0].Member_Account)
              if (That.type === 'add') {
                // 添加页面
                OwnerALLData[0].selectable = false  // 群主不可选
                // 好友列表
                That.friendLists.forEach(val => {  // 好友处理
                  // 群里没有好友账号的
                  val.selectable = false  // 全部不可选
                  if (!arr.includes(val.To_Account)) {
                    val.selectable = true // 可选
                  }
                })
                console.log('好友列表', That.friendLists);
                console.log('BUG,删除好友后，好友还在这个群里面');
                That.friendLists.unshift(OwnerALLData[0])   // 添加群主
                That.lastArr = That.friendLists;
              } else if (That.type === 'del') {
                // 删除页面
                // 去掉群主
                That.lastArr = That.groupLists.filter(val => val.To_Account !== ownerData[0].Member_Account)
              }
            })

          },
          (err) => {
            console.log(err.ErrorInfo);
          }
        );
      },
      // 获取全部好友
      getFriendList(loginInfo) {
        let getAllFriend = (cbOK, cbErr) => {
          let options = {
            From_Account: loginInfo.identifier,
            TimeStamp: 0,
            StartIndex: 0,
            GetCount: 100, //totalCount,
            LastStandardSequence: 0,
            TagList: [
              "Tag_Profile_IM_Nick",
              "Tag_Profile_IM_SelfSignature", //个性签名
              "Tag_Profile_IM_Image", //头像
              "Tag_Profile_IM_Gender", //性别
              "Tag_Profile_IM_AllowType", //加好友验证方式
              "Tag_Profile_IM_Location", //所在地
              "Tag_Profile_IM_BirthDay", //生日
              "Tag_Profile_IM_MsgSettings" //消息设置 置0表示接收消息，置1则不接收消息
            ]
          };
          webim.getAllFriend(
            options,
            (resp) => {
              console.log(resp);
              if (resp.FriendNum > 0) {
                //转化成对象挂载到数据
                for (let i = 0; i < resp.InfoItem.length; i++) {
                  if (resp.InfoItem[i].SnsProfileItem) {
                    let sns = resp.InfoItem[i].SnsProfileItem;
                    sns.forEach((ele, index) => {
                      resp.InfoItem[i][ele.Tag] = ele.Value;
                    });
                    resp.InfoItem[i]['To_Account'] = resp.InfoItem[i]['Info_Account']   // 用户ID 统一为  To_Account
                    // 删除属性
                    delete resp.InfoItem[i].SnsProfileItem
                  }
                }
                this.friendLists = resp.InfoItem;
                if (cbOK) cbOK();
              }
            },
            (err) => {
              console.log(err.ErrorInfo);
            }
          );
        };
        getAllFriend();
      },
      // 点击完成
      finish(){
        if (!this.selectArr.length) {
          Toast('请先选择成员')
          return
        }
        if (this.type === 'add') {
          // 添加
          let arr = []
          for (var i = 0; i < this.selectArr.length; i++) {
            let obj = {}
            obj['Member_Account'] = this.selectArr[i]
            arr.push(obj)
          }
          this.addGroupMember(arr)
        } else if (this.type === 'del') {
          MessageBox.confirm('确定执行此操作?').then(action => {
            this.deleteGroupMember(this.selectArr)
          }, () => {
          });
        }
      },
      // 邀请好友加群动作
      addGroupMember(friend_id) {
        let s = this;
        var options = {
          'GroupId': this.groupId,
          'MemberList': friend_id
        };
        webim.addGroupMember(
          options,
          (resp) => {
            Toast('邀请好友加群成功');
            history.back()
          },
          (err) => {
            console.log(err.ErrorInfo);
          }
        );
      },
      //删除群组成员
      deleteGroupMember(accountId) {
        var options = {
          'GroupId': this.groupId,
          //'Silence': $('input[name="dgm_silence_radio"]:checked').val(),//只有ROOT用户采用权限设置该字段（是否静默移除）
          'MemberToDel_Account': accountId
        };
        webim.deleteGroupMember(
          options,
          (resp) => {
            Toast('移除群成员成功');
            history.back()
          },
          (err) => {
            Client.errInfo;
            // alert(err.ErrorInfo);
          }
        );
      },
    }
  }

</script>
